package fr.labri.harmony.analysis.jsep.results.filter;

import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

import fr.labri.harmony.analysis.jsep.results.Counter;
import fr.labri.harmony.analysis.jsep.results.LoadRules;
import fr.labri.harmony.analysis.jsep.results.Pair;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;


public class MigrationComments extends ResultFilter {

	@Override
	public void computeResult(ResultSet rs) {
		try {
			rs.first();
			//Init DB
			Counter c = new Counter();
			//Commit log
			List<String> libs = new ArrayList<String>(Arrays.asList("hadoop-hive","leveldb","db4o"));
			while (rs.next()){
				String name = rs.getString("NAME");
				String lib_to = rs.getString("MIGRATION_LIB_TO");
				if(LoadRules.isTrueRule(name, lib_to)) {
					if(libs.contains(name) || libs.contains(lib_to)) {
					String project = rs.getString("PROJECT");
					String reason = rs.getString("MIGRATION_REASON");	
					c.incrComment(name, lib_to, project, reason);
					List<Pair<String,String>> msg1 = BugReportFinder.getMsg(project, name);
					for(Pair<String,String> msg : msg1)
						if(!msg.getElement1().isEmpty())
							c.incrCommentBugTracker(name, lib_to, project, msg);
					List<Pair<String,String>> msg2 = BugReportFinder.getMsg(project, lib_to);
					for(Pair<String,String> msg : msg2)
						if(!msg.getElement1().isEmpty() && !msg1.contains(msg))
							c.incrCommentBugTracker(name, lib_to, project, msg);
					}
				}
			}
			c.viewCSVCommitLogs(new FileOutputStream("Logs_migrations.csv"));
		} catch (SQLException | IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
}

class BugReportFinder {
	
	static int cpt = 1;
	static int cpt_issues = 1;
	
	static List<Pair<String,String>> getMsg(String project, String library) {
		System.out.println("Start getMsg");
		List<Pair<String,String>> listMsgs = new ArrayList<>();

		cpt++;
		if(cpt%19==0) {
			System.out.println(cpt+" requetes search vers les bugs trackers");
			try {
				Thread.sleep(60000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		System.out.println("Execute query...");
		try {
			HttpClient httpclient = HttpClientBuilder.create().build();
			String repouser = project.split("\\/")[project.split("\\/").length-2];
			String reponame = project.split("\\/")[project.split("\\/").length-1];

			//String url = "https://api.github.com/search/issues?q="+lib+"%2B%40"+repouser+"%2F"+reponame+"?client_id=2ed17e001bf33de40abc&client_secret=b0eab562ac53c793c606bd27ef40a9e5e4feefc1";
			String url = "https://api.github.com/search/issues?q="+library+"+%40"+repouser+"%2F"+reponame+"&client_id=2ed17e001bf33de40abc&client_secret=b0eab562ac53c793c606bd27ef40a9e5e4feefc1";
			System.out.println(url);
			HttpGet httpget = new HttpGet(url);
			httpget.addHeader("Accept", "application/vnd.github.preview");
			HttpResponse response = httpclient.execute(httpget);

			BufferedReader rd = new BufferedReader
					(new InputStreamReader(response.getEntity().getContent()));

			String line = "";
			String json = "";
			while ((line = rd.readLine()) != null) {
				json += line;
			}
			System.out.println("End Execute query...");

			ObjectMapper mapper = new ObjectMapper();
			JsonNode rootNode = mapper.readTree(json);
			JsonNode msgNode = rootNode.path("items");
			Iterator<JsonNode> ite = msgNode.elements();

			while (ite.hasNext()) {
				System.out.println("Browse new bug...");
				JsonNode temp = ite.next();
				StringBuffer content = new StringBuffer();
				content.append("\n");
				content.append("("+temp.get("body").asText()+")");
				content.append("\n");
				listMsgs.add(new Pair<String, String>(temp.get("url").asText(),content.toString()));
				if(temp.get("comments").asInt()>0) {
					System.out.println("Execute query comment...");
					String number = temp.get("number").asText();
					cpt_issues++;
					if(cpt_issues%4900==0) {
						System.out.println(cpt_issues+" requetes comments vers les bugs trackers");
						try {
							Thread.sleep(60000);
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
					}
					//https://api.github.com/repos/tibistibi/mTorClient/issues/3/comments
					String url_comment = "https://api.github.com/repos/"+repouser+"/"+reponame+"/issues/"+number+"/comments?client_id=2ed17e001bf33de40abc&client_secret=b0eab562ac53c793c606bd27ef40a9e5e4feefc1";
					System.out.println(url_comment);
					HttpClient httpclient_comment = HttpClientBuilder.create().build();
					HttpGet httpget_comment = new HttpGet(url_comment);
					HttpResponse response_comment = httpclient_comment.execute(httpget_comment);

					BufferedReader rd_comment = new BufferedReader
							(new InputStreamReader(response_comment.getEntity().getContent(),Charset.forName("UTF-8")));

					String line_comment = "";
					String json_comment = "";
					while ((line_comment =rd_comment.readLine()) != null) {
						json_comment += line_comment;
					}
					ObjectMapper mapper_comment = new ObjectMapper();
					JsonNode rootNode_comment = mapper_comment.readTree(json_comment);
					Iterator<JsonNode> ite_comments = rootNode_comment.elements();
					while (ite_comments.hasNext()) {
						JsonNode temp_comment = ite_comments.next();
						StringBuffer body = new StringBuffer();
						body.append("\n");
						if(temp_comment.get("body") !=null) {
							body.append("("+temp_comment.get("body").asText()+")");
							body.append("\n");
							listMsgs.add(new Pair<String, String>(temp_comment.get("url").asText(), body.toString())); 
						}
					}
					System.out.println("End Execute query comment...");
				}
				System.out.println("End Browse new bug...");
			}
			System.out.println("End getMsg");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return listMsgs;
	}
}


